/*
 * GTFSDBTable.java
 * 
 * Created by demory on Nov 11, 2009, 3:35:14 PM
 * 
 * Copyright 2008 David D. Emory
 * 
 * This file is part of Five Points. See <http://www.fpdev.org> for
 * additional information regarding the project.
 * 
 * Five Points is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Five Points is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Five Points.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.fpdev.core.transit.gtfs;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 *
 * @author demory
 */

public class GTFSDBTable {

  protected GTFSImporter importer_;
  protected GTFSDatabase db_;
  protected String name_;

  //private Type type_;

  protected Map<String, Integer> columnNames_;
  //protected List<String[]> rows_;

  /*public enum Type {
    CAL_DATES,
    ROUTES,
    TRIPS,
    SHAPES
  }*/

  public GTFSDBTable(String name, File file, GTFSImporter importer) {
    name_ = name;
    importer_ = importer;
    db_ = importer_.getDB();
    //type_ = type;
    columnNames_ = new HashMap<String, Integer>();
    //rows_ = new LinkedList<String[]>();


    if(!db_.tableExists(name_)) readFile(file);
    else columnNames_ = db_.getColumnNames(name_);
  }

  public void readFile(File file) {
    try {
      BufferedReader reader = new BufferedReader(new FileReader(file));
      String line = reader.readLine();

      
      // process column headings
      String cols[] = line.split(",");
      for(int i=0; i<cols.length; i++)
        columnNames_.put(cols[i], i+1);
      db_.createTable(name_, cols);
            
      // process data rows
      while((line = reader.readLine()) != null) {
        //rows_.add(line.split(","));

        List<String> data = new LinkedList<String>();
        for(String str : line.split(","))
          data.add(str);
        if(line.startsWith(",")) data.add(0, "");
        if(line.endsWith(",")) data.add(data.size(), "");

        db_.addRow(name_, data);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  public List<String[]> getData() {
    return db_.getData(name_);
  }

  public List<String[]> getData(String condition) {
    return db_.getData(name_, condition);
  }
}
